package com.hzy.quetosys.controller;

import com.hzy.quetosys.entity.User;
import com.hzy.quetosys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @GetMapping("/login")
    public ModelAndView loginView(){
        ModelAndView mav=new ModelAndView("login");
        return mav;
    }
    @PostMapping("/login")
    public ModelAndView login(
            @RequestParam(name = "username" ,required = true,defaultValue = "") String username,
            @RequestParam(name = "password" ,required = true,defaultValue = "") String password,
            HttpSession session

    ){
        ModelAndView mav=new ModelAndView("redirect:/index");
        User user=userService.findByNamePass(username,password);
        if(user != null){
            session.setAttribute("user",user);
        }else {
            mav.setViewName("redirect:/login");
        }
        return mav;
    }
    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session, SessionStatus sessionStatus){
        ModelAndView mav=new ModelAndView("redirect:/login");
        session.removeAttribute("user");
        session.invalidate();
        sessionStatus.setComplete();
        return mav;
    }
}
